package com.lagou.builder;

import com.lagou.config.Configuration;
import com.lagou.mapping.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        //sql
        List<Element> select = rootElement.selectNodes("select|update|insert|delete");
        for (Element element : select) {

            String id = element.attributeValue("id");
            String statementId = namespace+"."+id;
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(statementId);
            mappedStatement.setParameterType(element.attributeValue("parameterType"));
            mappedStatement.setResultType(element.attributeValue("resultType"));
            mappedStatement.setSql(element.getText());
            //为了便于区分sql语句，增加sqlType
            mappedStatement.setSqlType(element.getName());

            configuration.addMappedStatement(statementId,mappedStatement);
        }
    }

}
